package com.hnhegui.backend.order.service;

import com.hnhegui.backend.exception.BusinessException;
import com.hnhegui.backend.order.dto.request.FulfillmentRequestDTO;
import com.hnhegui.backend.order.dto.response.FulfillmentResponseDTO;
import com.hnhegui.backend.order.entity.OrderDocument;
import com.hnhegui.backend.order.enu.DeliveryTypeEnum;
import com.hnhegui.backend.order.enu.FulfillmentStatusEnum;
import com.hnhegui.backend.order.enu.OrderStatusEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Random;
import java.util.UUID;

/**
 * @author 刘大海
 * @since 2025/10/27 10:50
 */
@Service
public class FulfillmentService {

    @Autowired
    private OrderService orderService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public FulfillmentResponseDTO processFulfillment(FulfillmentRequestDTO request) {
        // 查询订单
        OrderDocument order = orderService.getOrderById(request.getOrderId());
        //todo 这里需要校验订单是否存在，不存在，下面会出现空指针问题
        // 验证订单状态（必须是已支付状态）
        if (order.getStatus() != OrderStatusEnum.PAID) {
            throw new BusinessException(40001, "订单状态不正确，无法履约");
        }

        // 初始化履约信息
        OrderDocument.Fulfillment fulfillment = new OrderDocument.Fulfillment();
        fulfillment.setFulfillmentType(request.getFulfillmentType());
        fulfillment.setFulfillmentTime(LocalDateTime.now());

        DeliveryTypeEnum deliveryType = DeliveryTypeEnum.getByName(request.getFulfillmentType());
        if (deliveryType == null) {
            throw new BusinessException(40001, "不支持的配送类型");
        }
        switch (deliveryType) {
            case EXPRESS -> {
                // 快递配送
                if (request.getExpressInfo() == null) {
                    throw new BusinessException(40001, "快递配送必须提供快递信息");
                }

                OrderDocument.ExpressInfo expressInfo = new OrderDocument.ExpressInfo();
                expressInfo.setExpressCompany(request.getExpressInfo().getExpressCompany());
                expressInfo.setTrackingNo(request.getExpressInfo().getTrackingNo());
                fulfillment.setExpressInfo(expressInfo);
                fulfillment.setFulfillmentStatus(FulfillmentStatusEnum.SHIPPED.name());

                order.setStatus(OrderStatusEnum.FULFILLING);
            }
            case PICKUP -> {
                // 门店自提
                if (request.getPickupInfo() == null) {
                    throw new BusinessException(40001, "门店自提必须提供自提信息");
                }

                OrderDocument.PickupInfo pickupInfo = new OrderDocument.PickupInfo();
                pickupInfo.setStoreId(request.getPickupInfo().getStoreId());
                // 生成6位提货码
                pickupInfo.setPickupCode(generatePickupCode());
                fulfillment.setPickupInfo(pickupInfo);
                //todo提取码信息需要持久化（不持久化没办法校验提取码是否正确）
                //将提取码持久到redis上
                redisTemplate.opsForValue().set("pickupCode:" + pickupInfo.getPickupCode(), order.getOrderId());
                fulfillment.setFulfillmentStatus(FulfillmentStatusEnum.READY_FOR_PICKUP.name());
                order.setStatus(OrderStatusEnum.FULFILLING);
            }
            case VIRTUAL -> {
                // 虚拟商品
                OrderDocument.VirtualInfo virtualInfo = new OrderDocument.VirtualInfo();

                if (request.getVirtualInfo() != null) {
                    virtualInfo.setActivationCode(request.getVirtualInfo().getActivationCode() != null ?
                        request.getVirtualInfo().getActivationCode() : generateActivationCode());
                    virtualInfo.setDownloadUrl(request.getVirtualInfo().getDownloadUrl());
                } else {
                    virtualInfo.setActivationCode(generateActivationCode());
                }

                fulfillment.setVirtualInfo(virtualInfo);
                fulfillment.setFulfillmentStatus(FulfillmentStatusEnum.ACTIVATED.name());

                // 虚拟商品直接完成
                order.setStatus(OrderStatusEnum.COMPLETED);
            }
            default -> throw new BusinessException(40001, "不支持的配送类型");
        }
        order.setFulfillment(fulfillment);

        // 保存订单
        orderService.updateOrder(order);

        // 构建响应
        FulfillmentResponseDTO response = new FulfillmentResponseDTO();
        response.setOrderId(order.getOrderId());
        response.setFulfillmentStatus(fulfillment.getFulfillmentStatus());
        response.setFulfillmentTime(fulfillment.getFulfillmentTime());

        return response;
    }

    /**
     * 生成6位提货码
     */
    private String generatePickupCode() {
        Random random = new Random();
        return String.format("%06d", random.nextInt(1000000));
    }

    /**
     * 生成激活码
     */
    private String generateActivationCode() {
        return UUID.randomUUID().toString().replace("-", "").toUpperCase().substring(0, 16);
    }
}
